import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Store from '../store'
import NotFonten from '../views/404.vue'

Vue.use(VueRouter)
Vue.use(Store)
const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    component: Home
  },
  {
    // 全部商品
    path: '/allgoods',
    name: 'Allgoods',
    component: () => import(/* webpackChunkName: "allgoods" */ '../views/AllGoods.vue')
  },
  {
    // 我的订单
    path: '/myorder',
    name: 'MyOrder',
    component: () => import('../views/MyOrder.vue')
  },
  {
    // 个人中心
    path: '/personalcenter',
    name: 'PersonalCenter',
    component: () => import('../views/PersonalCenter.vue'),
    children: [
      {
        path: 'centers',
        name: 'Center',
        component: () => import(/* webpackChunkName: "center" */ '../components/Center.vue'),
      },
      {
        path: 'cart',
        name: 'Cart',
        component: () => import(/* webpackChunkName: "cart" */ '../components/Cart.vue'),
      }
    ]
  },
  {
    // 专属福利
    path: '/welfare',
    name: 'Welfare',
    component: () => import('../views/Welfare.vue')
  },
  {
    // 商品详情
    path: '/details/:id',
    name: 'Details',
    component: () => import('../views/Details.vue')
  },
  {
    path: '*',
    component: NotFonten
  }
]


const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 解决重复点击相同路由是会发生报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 路由导航
router.beforeEach((to, from, next) => {
  if (to.path === '/personalcenter') {
    // 当用户要跳转到个人中心页面的时候，判断是否登录  也就是是否有token
    let token = localStorage.getItem('x-auth-token')
    if (token) {
      next()
    } else {
      // 给出‘请先登录’的提示信息
      Store.dispatch('asyncclosetoast', { content: '请先登录！', icon: 'info' })
    }
    return;
  }
  next()
})

export default router
